import React from 'react'
import { connect } from 'react-redux'
import { validForm as validFormDuck } from 'ducks'
import { Button } from 'semantic-ui-react'
import PropTypes from 'prop-types'
import produce from 'immer'

const ValidFormSubmit = ({
  graphqlAddtodo,
  submitValues,
  isFormValid,
  children,
  variables,
  ...otherProps
}) => {
  const variablesFinal = produce(submitValues, (draftState) => {
    if (variables) draftState = Object.assign(submitValues, variables)
  })
  return (
    <Button
      disabled={!isFormValid}
      onClick={() => graphqlAddtodo({ variables: variablesFinal })}
      {...otherProps}
    >
      {children}
    </Button>
  )
}

ValidFormSubmit.propTypes = {
  isFormValid: PropTypes.bool.isRequired,
  submitValues: PropTypes.object.isRequired,
  children: PropTypes.node.isRequired,
}

const mapStateToProps = (state, ownProps) => ({
  isFormValid: validFormDuck.selectors.isFormValid(state),
  submitValues: validFormDuck.selectors.submitValues(state, ownProps.graphqlParams),
})

export default connect(
  mapStateToProps,
  null,
)(ValidFormSubmit)
